package spring.chatroom.java_chatroom.common.utils;

import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;


/**
 * 将webSession和userId映射起来 不能使用sessionId 因为分辨不出是谁的webSession
 * 改为redis
 */
public class WebSocketSessionManagerUtil {

    static ConcurrentHashMap<Integer, WebSocketSession> sessionMap = new ConcurrentHashMap<>();
    static ConcurrentHashMap<WebSocketSession, Integer> sessionMapRev = new ConcurrentHashMap<>();

    public static void setAttribute(Integer userId, WebSocketSession session) {
        //todo 同一个id多个Session的处理
        sessionMap.put(userId, session);
        sessionMapRev.put(session, userId);
    }

    public static ConcurrentHashMap<Integer, WebSocketSession> getMap() {
        return sessionMap;
    }

    public static WebSocketSession getAttribute(Integer UserId) {
        return sessionMap.get(UserId);
    }

    public static WebSocketSession removeAttribute(Integer userId) {
        if (!sessionMap.containsKey(userId)) {
            return null;
        }

        WebSocketSession remove = sessionMap.remove(userId);
        sessionMapRev.remove(remove);
        return remove;
    }

    public static Integer removeAttribute(WebSocketSession session) {
        if(!sessionMapRev.containsKey(session)) {
            return null;
        }

        Integer remove = sessionMapRev.remove(session);
        sessionMap.remove(remove);
        return remove;
    }

    public static Integer getUserId(WebSocketSession session) {
        return sessionMapRev.get(session);
    }

    public static WebSocketSession getSession(Integer UserId) {
        return sessionMap.get(UserId);
    }
}
